package com.allen.mk.admin.springsecurity.service;


import com.allen.mk.admin.entity.SysUser;
import com.allen.mk.admin.mapper.SysUserMapper;
import com.allen.mk.admin.service.impl.SysUserServiceImpl;
import com.allen.mk.admin.springsecurity.entity.SelfUserEntity;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.stream.Collectors;

@Component
@Slf4j
public class SelfUserDetailsService implements UserDetailsService {



    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysUserServiceImpl userService;
    @Override
    public SelfUserEntity loadUserByUsername(String username) throws UsernameNotFoundException {

//        log.info("2");
        // 查询用户信息
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        SysUser user = sysUserMapper.selectOne(queryWrapper.eq("user_name",username));
        if (user != null){
            // 组装参数
            SelfUserEntity selfUserEntity = new SelfUserEntity();
            BeanUtils.copyProperties(user,selfUserEntity);
            selfUserEntity.setAuthorities(userService.getAuthorities(username).stream()
                            .map(o -> o.getRoleName()).collect(Collectors.toList()).stream()
                            .map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
            selfUserEntity.setUsername(user.getUserName());
            return selfUserEntity;
        }else {
            throw new UsernameNotFoundException("用户名不存在~~~");
        }
    }
}
